import hexfield
import Map
import GameRender
import sqlite_utils
import glgui2
import cPickle
class Side:
  def __init__(self):
    self.name = None
    self.group = None

class Soldier:
  """morale - surrendered,fleeing,panics,scared,pinned,caution,normal,aggressive,heroic,berserk"""
  """status - KIA,uncnocious,hwound,lwound,normal"""
  """rank - private,efreitor,sergeant,mlieutenantm,lieutenant,captian,mayor"""
  """Note:gunners use vehicle weapons as weapon"""
  
  def calcualte_firepower(self):
    pass
  
  def calculate_precission_hit(self,enemy):
    pass
  
  def calculate_defense(self):
    pass
  
  def __init__(self,specialization):
    #parameters should be described well
    
    self.specialization,self.ammunition,self.additional_ammunition \
    = sqlite_utils.sql_exec("""SELECT specialization,ammunition,additional_ammunition from soldiers where specialization='"""+specialization+"'")[0]
    
    self._side = None
    self._rank = 'private'
    self._expirience = 0
    self._status = 'normal'
    self._morale_status = 'normal'
    self._stamina = 'normal'

class Vehicle:
  """status - active,damaged,immobilized,burning,destroyed"""
  def __init__(self,type):
    self.model = type
    self.type,self.ammunition,self.additional_ammunition,fuel \
    = sqlite_utils.sql_exec("""SELECT type,main_ammunition,secondary_ammunition,fuel from vehicles where model='"""+type+"'")[0]
    self.status = 'active'
  
def str_to_list(string):
  tmp = string.split(',')
  ret = []
  for element in tmp:
    if '*' in element:
      element = element.split('*')
      ret = ret + [element[0]]*int(element[1])
    else:
      ret.append(element)
  return ret
      
class Group:
  def __init__(self,fireteams,commander):
    self.type = ''
    self.subgroups = []
    self.formation = 'column'
    self.state = 'non-combat'
    self.commander = commander
    
class Fireteam:
  def calculate_speed(self):
    pass
    
  def __init__(self,name = '' ,type = '',x = 0 ,y = 0,marker = None):
    self.group = None
    self.x = x
    self.y = y
    self.name = name
    self.type = type
    self.vehicles = []
    self.soldiers = []
    self.tactical_orders = []
    self.operational_orders = []
    self.marker = None
    self.selection_marker = None
    if type != '':
      qry = sqlite_utils.sql_exec("""SELECT * from fireteams where name='"""+type+"'")
      for element in qry[0]:
        if len(sqlite_utils.sql_exec("""SELECT specialization from soldiers where specialization='"""+element+"'")):
          self.soldiers.append(Soldier(element))
        elif  len(sqlite_utils.sql_exec("""SELECT model from vehicles where model='"""+element+"'")):
          self.vehicles.append(Vehicle(element))
  def update_marker(self):
    pass
  def __del__(self):
    if not self.marker is None: 
      self.marker.delete()
      self.selection_marker.delete()
    
  def write(self,file):
    cPickle.dump((self.x,self.y,self.name,self.type,self.vehicles,self.soldiers),file)
    
  def read(self,file):
    self.x,self.y,self.name,self.type,self.vehicles,self.soldiers =  cPickle.load(file)
    
    
    
class Platoon(Group):
  def __init__(self,name = '',type = ''):
    self.group = None
    self.name = name
    self.type = type
    self.groups = []
    
  def write(self,file):
    cPickle.dump(( self.name, self.type),file)
    cPickle.dump(len(self.groups),file)
    for group in self.groups:
      group.write(file)
  
  def read(self,file):
    self.name, self.type = cPickle.load(file)
    count = cPickle.load(file)
    self.groups = []
    for i in range(count):
      group = Fireteam()
      group.read(file)
      group.group = self
      self.groups.append(group)
  
class Company(Group):
  def __init__(self,name):
    self.name = name
    self.groups = []
  
  def write(self,file):
    cPickle.dump(self.name,file)
    cPickle.dump(len( self.groups),file)
    for group in self.groups:
      cPickle.dump(group.__class__.__name__,file)
      group.write(file)
  
  def read(self,file):
    self.groups = []
    self.name = cPickle.load(file)
    count = cPickle.load(file)
    for i in range(count):
      type = cPickle.load(file)
      if type == 'Fireteam':
        group = Fireteam()
        group.read(file)
        group.group = self
        self.groups.append(group)
      else:
        group = Platoon()
        group.read(file)
        group.group = self
        self.groups.append(group)

class Side:
  def __init__(self,name):
    self.name = name
    self.companies = [Company('mro1'),Company('mro2'),Company('mro3')]
  
  def write(self,file):
    cPickle.dump(self.name,file)
    self.companies[0].write(file)
    self.companies[1].write(file)
    self.companies[2].write(file)
  
  def read(self,file):
    self.name = cPickle.load(file)
    self.companies = [Company('mro1'),Company('mro2'),Company('mro3')]
    self.companies[0].read(file)
    self.companies[1].read(file)
    self.companies[2].read(file)
    
    
  def add_company(self,name,type):
    self.companies.append(Company(name))
  
  def add_fireteam_to_platoon(self,platoon,name,type,x,y):
    fireteam = Fireteam(name,type,x,y)
    fireteam.group = platoon
    platoon.groups.append(fireteam)
    return fireteam
    
  def add_platoon(self,company,name,type):
    self.companies[company].groups.append(Platoon(name,type))
    
    return self.companies[company].groups[-1]
  
  def add_fireteam(self,company,name,type,x,y):
    self.companies[company].groups.append(Fireteam(name,type,x,y))
    return self.companies[company].groups[-1]

  
def get_list(line):
  ret = line
  for element in line:
    if '*' in element:
      print int(element.split('*')[1])
      for a in range(int(element.split('*')[1])):
        ret.append(element.split('*')[0])
      ret.remove(element)
  return ret
  
class Mission:
  def __init__(self,map):
    self.selected_fireteams = []
    self.map = map
    self.sides = {}
    for name in sqlite_utils.get_line("""SELECT name FROM sides"""):
      self.sides[name] = Side(name)
      
    self.structures = []
    self.map = map
    self.markers = hexfield.HexfieldMarkers(self.map.hexfield)
    
    self.map.hexfield.add_markers(self.markers)
    
    self.iconset = GameRender.Iconset()
    self.selection_img = self.iconset.dictionary['cursor']
    self.selection = []
   # self.path = hexfield.HexfieldPath(self.map.hexfield,color = (255,255,0))
   # self.map.hexfield.add_markers(self.path)
    
  def add_fireteam(self,side,company,ft,x,y,platoon = None):
    x,y = self.map.hexfield.tile_pos(x,y)
    fireteam = None
    print platoon
    if platoon is None:
      fireteam = self.sides[side].add_fireteam(company,'ft',ft,x,y)
      fireteam.group = self.sides[side].companies[company]
    else:
       fireteam = self.sides[side].add_fireteam_to_platoon(platoon,'temp',ft,x,y)
       
    fireteam.marker = self.markers.add(glgui2.sprite(self.iconset.dictionary[ft]),x,y)
    fireteam.selection_marker = self.markers.add(glgui2.sprite(self.iconset.dictionary['cursor']),x,y)
    fireteam.selection_marker.visible = False
    color = glgui2.string_to_rgb(sqlite_utils.get_value("""SELECT color FROM sides WHERE name='"""+side+"""'"""))
    fireteam.marker._set_color(color)
    
    return fireteam
  

  def update_markers(self):
    for name in self.sides:
      color = glgui2.string_to_rgb(sqlite_utils.get_value("""SELECT color FROM sides WHERE name='"""+name+"""'"""))
   
      for company in self.sides[name].companies:
        for group in company.groups:
          if group.__class__.__name__=='Fireteam':
            fireteam = group
            ft = group.type
            fireteam.marker = self.markers.add(glgui2.sprite(self.iconset.dictionary[ft]),fireteam.x,fireteam.y)
            fireteam.selection_marker = self.markers.add(glgui2.sprite(self.iconset.dictionary['cursor']),fireteam.x,fireteam.y)
            fireteam.selection_marker.visible = False
            fireteam.marker._set_color(color)
          else:
            for fireteam in group.groups:
              ft = fireteam.type
              fireteam.marker = self.markers.add(glgui2.sprite(self.iconset.dictionary[ft]),fireteam.x,fireteam.y)
              fireteam.selection_marker = self.markers.add(glgui2.sprite(self.iconset.dictionary['cursor']),fireteam.x,fireteam.y)
              fireteam.selection_marker.visible = False
              fireteam.marker._set_color(color)
        
      
  
  def write(self,name):
    file = open(name,'wt')
    cPickle.dump(len(self.sides),file)
    for name in self.sides:
      cPickle.dump(name,file)
    for name in self.sides:
      self.sides[name].write(file)
  
  def read(self,name):
    self.clear_selection()
    self.markers.clear()
    
    file = open(name)
    count = cPickle.load(file)
    self.sides = {}
    for i in range(count):
      name = cPickle.load(file)
      self.sides[name] = Side(name)
    for name in self.sides:
      self.sides[name].read(file)
    self.update_markers()
      
  def add_platoon(self,side,company,platoon_name,x,y):
    x,y = self.map.hexfield.tile_pos(x,y)
    platoon = self.sides[side].add_platoon(company,'pt',platoon_name)
    platoon.group = self.sides[side].companies[company]
    line = sqlite_utils.get_value("""SELECT contains FROM platoons WHERE name='"""+platoon_name+"""'""")
    color = glgui2.string_to_rgb(sqlite_utils.get_value("""SELECT color FROM sides WHERE name='"""+side+"""'"""))
    line = get_list(line.split(','))
    for ft in line:
      fireteam = self.sides[side].add_fireteam_to_platoon(platoon,'temp',ft,x,y)
      fireteam.marker = self.markers.add(glgui2.sprite(self.iconset.dictionary[ft]),x,y)
      fireteam.marker._set_color(color)
      fireteam.selection_marker = self.markers.add(glgui2.sprite(self.iconset.dictionary['cursor']),x,y)
      fireteam.selection_marker.visible = False
      
  def remove_fireteam(self,x,y,ft):
    pass
    
  def remove_platoon(self,platoon):
    self.remove_fireteams(platoon.groups)
    platoon.group.groups.remove(platoon)
    platoon.groups = []
    del platoon
    
  def remove_fireteams(self,ftms):
    for ft in list(ftms):
      ft.group.groups.remove(ft)
      self.selection.remove(ft)
      print ft.group.groups,ftms
      if ft.group.__class__.__name__ == 'Platoon' and len(ft.group.groups)==0:
        self.remove_platoon(ft.group)
    
  
  def clear_selection(self):
    for ft in self.selection:
      ft.selection_marker.visible = False
    self.selection = []
    
  def unselect_fireteam(self,ft):
    self.select.remove(ft)
    ft.selection_marker.visible = False
  
  def select_fireteams(self,ftms):
    for ft in ftms:
      self.select_fireteam(ft)
      
  def select_fireteam(self,ft):
    self.selection.append(ft)
    ft.selection_marker.visible = True
  
  def select_platoon(self,pt):
    pass
    
  def unselect_platoon(self,pt):
    pass
  
  def select_company(self,cmpm):
    pass
  def unselect_company(self,cmpn):
    pass
      
  def rotate_fireteam_markers(self,x,y):
    x,y = self.map.hexfield.tile_pos(x,y)
    self.markers.rotate_markers(x,y)
  
  def draw(self):
    
    pass
    #self.markers.draw()
    
    
class MissionIngame:
  pass

